package com.infore.airsupervise.http;

import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.infore.airsupervise.R;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MyApplication;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.ProgressBean;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.other.ProgressHandler;
import com.infore.airsupervise.other.listener.LoaderProgressListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

/**
 * 网络请求工具类
 *
 * @author: dingxinlin
 * @date: 2016-11-17 17:35
 */

public class HttpUtil {

    private static int TIME_OUT = 15;

    private static HttpUtil instance;
    private static HttpService httpService;


    private HttpUtil() {}

    /**
     * 获取工具类实例
     * @return
     */
    public static HttpUtil getInstance() {
        if (instance == null) {
            instance = new HttpUtil();
        }
        return instance;
    }

    /**
     * 获取HttpService实例
     * @return
     */
    public static HttpService getHttpService() {
        if (httpService == null) {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            UserE userE= UserE.getUserInfo();
                            Request originalRequest  = chain.request();

                            if(userE!=null) {
                                Request.Builder builder= originalRequest.newBuilder();
                                Request requestBuilder = builder.addHeader(Constants.REQUESTHEAD_KEY, userE.getToken() == null ? "" : userE.getToken())
                                        .addHeader("currentId", userE.getUserId() == null ? "" : userE.getUserId())
                                        .build();
                                return  chain.proceed(requestBuilder);
                            }else {
                                return chain.proceed(originalRequest);
                            }
                        }
                    })
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(HttpAPI.ROOT_URL)
                    .addConverterFactory(FastJsonConverterFactory.create())
                    .client(client)
                    .build();
            httpService = retrofit.create(HttpService.class);
        }
        return httpService;
    }

    public static HttpService getLoadHttpService(final ProgressHandler mProgressHandler ,
                                                 final ProgressBean progressBean){
        //该方法在子线程中运行
        final LoaderProgressListener progressListener = new LoaderProgressListener() {
            @Override
            public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
                Log.d("progress:",String.format("%d%% done\n",(100 * bytesRead) / contentLength));
                if (mProgressHandler == null){
                    return;
                }

                progressBean.setBytesRead(bytesRead);
                progressBean.setContentLength(contentLength);
                progressBean.setDone(done);
                mProgressHandler.sendMessage(progressBean);

            }
        };
        OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .addInterceptor(new Interceptor() {

                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Response originalResponse  = chain.proceed(chain.request());
                            Response.Builder builder= originalResponse.newBuilder();
                            return builder.body(new ProgressResponse(originalResponse.body(),progressListener)).build();
                        }
                    })
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(HttpAPI.ROOT_URL)
                    .addConverterFactory(FastJsonConverterFactory.create())
                    .client(client)
                    .build();

        return retrofit.create(HttpService.class);
    }

    /**
     * 文件路径列表 转 MultipartBody
     * @param paths
     * @return
     */
    public MultipartBody filesToBody(List<String> paths) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        for (String uri : paths) {
            File file = new File(uri);
            if(file.exists()) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("file/dxl"), file);
                builder.addFormDataPart(file.getName(), file.getName(), requestBody);
            }
        }
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    /**
     * 文件路径列表 转 MultipartBody.Part列表
     * @param paths
     * @return
     */
    public List<MultipartBody.Part> filesToBodyParts(String key ,List<String> paths) {
        List<MultipartBody.Part> parts = new ArrayList<>();
        if(null != paths ){
        for (String uri : paths) {
            File file = new File(uri);
            if(file.exists()) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("file/dxl"), file);
                MultipartBody.Part part = MultipartBody.Part.createFormData(key, file.getName(), requestBody);
                parts.add(part);
            }
        }
        }
        return parts;
    }

    /**
     * 普通参数列表 转 MultipartBody.Part
     * @param params
     * @return
     */
    public List<MultipartBody.Part> paramsToBodyParts(Map<String, Object> params) {
        List<MultipartBody.Part> parts = new ArrayList<>();
        for(Map.Entry<String, Object> entry : params.entrySet()){
            MultipartBody.Part part = MultipartBody.Part.createFormData(entry.getKey(), entry.getValue().toString());
            parts.add(part);
        }
        return parts;
    }

    /**
     * 判断网络是否连接
     * @return
     */
    public boolean isNetworkOk() {
        ConnectivityManager connectivity =
                (ConnectivityManager) MyApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info == null || !info.isAvailable()) {
                return false;
            }
        }
        return true;
    }

    /**
     * Gps是否打开
     * @return
     */
    public boolean isOpenGps() {
        LocationManager locationManager =
                ((LocationManager) MyApplication.getInstance().getSystemService(Context.LOCATION_SERVICE));
        List<String> accessibleProviders = locationManager.getProviders(true);
        return accessibleProviders != null && accessibleProviders.size() > 0;
    }

    /**
     * 判断当前网络是否是wifi网络
     * @return boolean
     */
    public boolean isWifi() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) MyApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    /**
     * 根据错误码返回空试图
     * @param errorCode
     * @return
     */
    public static int getEmptyRes(int errorCode){
        switch (errorCode) {
            case StatusConst.CODE_CONNECT_FAIL:
              return  R.drawable.status_connect_failed;

            case StatusConst.CODE_CONNECT_TIMEOUT:
                return R.drawable.status_timeout;

            case StatusConst.CODE_SERVER_EXCEPTION:
                return R.drawable.status_server_fix;

            case StatusConst.CODE_OPERATION_FAIL:
                return R.drawable.status_connect_failed;
            default:
                return R.drawable.status_connect_failed;
        }
    }

}
